<template>
  <div class="app-container">
    <el-form ref="refForm" :inline="true" :model="filters" class="demo-form-inline filter-container">
      <el-form-item prop="dateType">
        <el-select v-model="filters.dateType">
          <el-option
            label="新建时间"
            :value="1">
          </el-option>
          <el-option
            label="修改时间"
            :value="2">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间：" prop="time">
        <el-date-picker
          v-model="filters.time"
          class="filter-item"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="部门岗位类别：" prop="department">
        <el-cascader
          change-on-select
          :options="options"
          v-model="filters.department"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="账户名：" prop="username">
        <el-input v-model="filters.username"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="filters.status">
          <el-option label="全部" :value="-1"></el-option>
          <el-option label="正常" :value="0"></el-option>
          <el-option label="锁定" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="修改人" prop="modifier">
        <el-select v-model="filters.modifier" clearable>
          <el-option
            v-for="item in modifierList"
            :label="item"
            :key="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" v-waves icon="el-icon-search" @click="submitFilterForm">搜索</el-button>
      <el-button @click="selfResetForm('refForm')">重置</el-button>
    </el-form>

    <el-table :data="tableData.list" v-loading="loading" element-loading-text="给我一点时间" border fit
              highlight-current-row
              style="width: 100%">
      <el-table-column label="新建时间" align="center" width="160px">
        <template slot-scope="scope">
          {{scope.row.createTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="部门类别" align="center" width="120px">
        <template slot-scope="scope">
          <el-tag>{{scope.row.departmentName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="岗位类别" width="120" align="center">
        <template slot-scope="{row}">
          <el-tag>{{row.jobName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="账户名" align="center">
        <template slot-scope="scope">
          {{scope.row.username}}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark">
      </el-table-column>
      <el-table-column label="状态" width="80px" align="center">
        <template slot-scope="{row}">
          <el-tag type="danger" v-if="row.status === 1">锁定</el-tag>
          <el-tag v-else>正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" width="100px" prop="lastOperator">
      </el-table-column>
      <el-table-column label="修改时间" align="center" width="160px">
        <template slot-scope="{row}">
          {{row.lastUpdate | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template slot-scope="{row}">
          <el-button type="text" @click="resetAuthenticationCode(row)">重置身份验证码</el-button>
          <el-button type="text" v-if="row.status === 0 && roleCheck('switch')" @click="toggleDepartment(row, 'close')">锁定</el-button>
          <el-button type="text" v-else-if="roleCheck('switch')" @click="toggleDepartment(row, 'open')">开启</el-button>
          <el-button v-if="roleCheck('edit')" type="text"
                     @click="openDialog({dialogName: 'edit-account-dialog',
                     props: row
                     })">
            编辑账户
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <edit-account-dialog v-if="dialogName === 'edit-account-dialog'"
                         v-model="dialogVisible"
                         :job-id="dialogProps.jobId"
                         :row-data="dialogProps"
                         @submit="submitFinished"/>
    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="tableData.total">
      </el-pagination>
    </div>

    <reset-authentication-code v-if="resetDialogVisible" :dialogVisible="resetDialogVisible" :row-data="rowData" @close="setDialogVisible(false)" />
  </div>
</template>

<script>
import { form, grid, dialog } from '@/build';

import {
  authAccountApi,
  authDepartmentAllGetApi,
  authAccountToggleApi,
  authModifierAllGetApi,
} from '@/services/api/permission';

import EditAccountDialog from './editAccountDialog';
import ResetAuthenticationCode from './resetAuthenticationCode';

export default {
  name: 'account-setting-de',

  mixins: [form, grid, dialog],

  components: {
    EditAccountDialog,
    ResetAuthenticationCode,
  },

  props: {
    departmentId: Number,
    jobId: Number,
  },

  data() {
    const { departmentId, jobId } = this.$route.query;
    return {
      options: [],
      tableData: {
        list: [],
        total: 0,
      },
      filters: {
        // departmentId: this.departmentId,
        // department: [this.departmentId, this.workId],
        dateType: 1,
        time: [moment(consts.ONLINE_DATE).format('YYYY-MM-DD HH:mm:ss'), moment().format('YYYY-MM-DD 23:59:59')],
        username: undefined,
        modifier: undefined,
        department: [parseInt(departmentId) || undefined, parseInt(jobId) || undefined],
        page: 1,
        size: 20,
        status: -1,
      },
      modifierList: [],
      resetDialogVisible: false,
      rowData: undefined,
    };
  },

  methods: {
    setDialogVisible(flag) {
      this.resetDialogVisible = flag;
    },
    resetAuthenticationCode(row) {
      this.rowData = row;
      this.setDialogVisible(true);
    },
    selfResetForm(formName) {
      this.resetForm(formName);
      this.gridSearch();
    },
    toggleDepartment({ userId, status }, type = 'open') {
      const display = type === 'open' ? '开启' : '锁定';

      this.$confirm(`确定要${display}此账户的登录权限吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        authAccountToggleApi({
          userId,
          status: status === 0 ? 1 : 0,
        }).then(([result, data]) => {
          if (result) {
            this.getAll();
            this.$message({
              type: 'success',
              message: `${display}成功!`,
            });
          } else {
            this.$message({
              type: 'error',
              message: `${display}失败!${data.message}`,
            });
          }
        });
      })
        .catch(() => {
        });
    },

    submitFilterForm() {
      const { time, department } = this.filters;
      let
        fromDate;
      let endDate;
      let departmentId;
      let jobId;
      if (!_.isUndefined(department) && _.isArray(department)) {
        departmentId = department[0];
        jobId = department[1];
      }
      if (!_.isUndefined(time) && _.isArray(time)) {
        fromDate = time[0];
        endDate = time[1];
      } else {
        this.filters.fromDate = undefined;
        this.filters.endTime = undefined;
      }
      this.filters = {
        ...this.filters, fromDate, endDate, departmentId, jobId,
      };
      this.gridSearch();
    },
  },

  mounted() {
    this.bindGet(authModifierAllGetApi, 'modifierList');
    this.bindGet(authDepartmentAllGetApi, 'options', {
      format: list => _.map(list, data => ({
        value: data.departmentId,
        label: data.name,
        children: _.map(data.jobList, childrenInfo => ({
          value: childrenInfo.jobId,
          label: childrenInfo.name,
        })),
      })),
    });

    this.bindGet(authAccountApi, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });

    this.getAll();
  },
};
</script>
